<template>
    <div class="view-fill">
      <div
        v-if="!modifyInfo.visible"
        class="app-container-flex"
      >
        <NewFullScreen
          v-model="showDialog"
          title="采购计划详情"
          :needOperateAffair="true"
          :operateAffairData="affairTableInfo"
          :needReturn="!$route.query.processInstanceId"
          @returnBack="returnBack"
        >
          <template v-slot:full-button>
            <!-- <el-button
              v-if="$permission('purchPlan:excelOrderDetail') && infoList.data.status != 1"
              @click="exportExcel"
              >导出excel</el-button
            >
            <PopoverPrint
              ref="popoverShow"
              v-model:popoverVisible="popoverVisible"
              :canPrint="canPrint"
              :templateArr="templateArr"
              @tempClick="tempClick"
              @print="print"
            ></PopoverPrint> -->
            <el-button v-if="canSubmit" @click="handelMethodRequest(infoList.data, 'submit')">提交</el-button>
            <el-button v-if="canUpdate" @click="update">修改</el-button>
            <el-button v-if="canModifyApplication" @click="modifyApplication">修改申请</el-button>
            <el-button v-if="canApprove" @click="handelMethodRequest(infoList.data, 'approved')"
              >批准</el-button
            >
            <el-button v-if="canReject" @click="handelMethodRequest(infoList.data, 'reject')"
              >驳回</el-button
            >
            <el-button v-if="canRefuse" @click="handelMethodRequest(infoList.data, 'refuse')"
              >拒绝</el-button
            >
            <el-button v-if="canRecall" @click="handelMethodRequest(infoList.data, 'revoke')">撤回</el-button>
            <el-button v-if="canSalesReview" @click="handelMethodRequest(infoList.data, 'cancelCheck')">销审</el-button>
          </template>
          <div class="model-panel">
            <div class="model-panel-title">
              <p>{{ $t('basic_information') }}</p>
            </div>
            <div class="model-panel-body">
              <basic-information :info="infoList" />
            </div>
          </div>
  
          <div class="model-panel" v-if="infoList.data.planDimension == '2'">
            <div class="model-panel-title">
              <Tooltip :text="$t('detailInfo')" />
            </div>
            <div class="model-panel-body">
              <div class="flex_full_item">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :check-box="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :isDynamic="true"
                >
                </page-table>
              </div>
            </div>
          </div>
        </NewFullScreen>
      </div>
      <!-- 修改 -->
      <Modify
        v-if="modifyInfo.visible"
        v-model:visible="modifyInfo.visible"
        :title="modifyInfo.title"
        :id="modifyInfo.orderId"
        :isDisabled="modifyInfo.isDisabled"
        @returnModify="refreshDetail"
      />
    </div>
  </template>
  
  <script setup>
  import {
    getPurchPlanById,
    getPurchProductDetail,
    methodPurchPlan
  } from '@/api/purch.js'
  import { orderOpAffairAll } from '@/api/affair'
  import Modify from './modify'
  import { doPrint } from '@/utils/exportUtil.js'
  import { selectByCodeAndDept } from '@/api/report.js'
  const { proxy } = getCurrentInstance()
  const emits = defineEmits()
  const props = defineProps(['visible', 'id'])
  
  const infoList = ref({
    data: {},
    fieldList: [
      { label: '单号', value: 'orderNo', type: 'text' },
      { label: '状态', value: 'statusValue', type: 'text' },
      { label: '计划名称', value: 'planName', type: 'text' },
      { label: '计划周期', value: 'planCycleValue', type: 'text' },
      { label: '年度', value: 'planYear', type: 'text' },
      { label: '季度', value: 'planQuarterValue', type: 'text', show: false, },
      { label: '月度', value: 'planMonthValue', type: 'text', show: false, },
      { label: '计划开始日期', value: 'planStartDate', type: 'text', show: true, },
      { label: '计划截止日期', value: 'planEndDate', type: 'text',  show: true, },
      { label: '计划维度', value: 'planDimensionValue', type: 'text' },
      { label: '计划金额值', value: 'planAmount', type: 'text', show: true, },
      { label: '计划范围', value: 'planRangeValue', type: 'text' },
      { label: '范围值', value: 'rangeIdValue', type: 'text', show: false },
      { label: '超量是否限制', value: 'isLimitValue', type: 'text' },
      { label: '限制业务', value: 'limitBusinessValue', type: 'text', show: true, },
      { label: '临界是否提醒', value: 'isCriticalRemindValue', type: 'text' },
      { label: '临界值(%)', value: 'criticalValue', type: 'text', show: true, },
      { label: '备注', value: 'remark', type: 'popover' },
    ],
  })
  // 过滤相关配置
  const filterInfo = ref({
    query: {
        purchPlanId: props.id,
    },
  })
  const modifyInfo = ref({
    visible: false,
    orderId: '',
    isDisabled: false,
    title: '',
  })
  // 表格相关
  const tableInfo = ref({
    refresh: 1,
    initCurpage: 1,
    data: [],
    fieldList: [
        { label: '产品名称', value: 'commonName' },
        { label: '产品编码', value: 'productCode' },
        { label: '产品规格', value: 'standard' },
        { label: '厂家名称', value: 'brandName' },
        { label: '库存单位', value: 'unitName' },
        { label: '计划数量', value: 'planNumber'},
        { label: '计划金额', value: 'planAmount', permission: !proxy.$permission('purchPlan:price') },
    ],
  })
  const affairTableInfo = ref({
    api: orderOpAffairAll,
    query: {
      orderType: 117,
      orderId: props.id,
      sort: 'operate_time desc',
    },
  })
  
  const showDialog = computed({
    get() {
      return props.visible
    },
    set(newValue) {
      emits('update:visible', newValue) // 更新父组件visible
    },
  })
  getMain()
  //状态: 待提交:1,待审核:2,审批中:3,待调整:4,已完成:5,已中止：6,已驳回：7,已拒绝：8
  //提交
  const canSubmit = computed(() => {
    return (
      proxy.$permission('purchPlan:submit') &&
      (infoList.value.data.status == 1 || infoList.value.data.status == 4)
    )
  })
  //批准
  const canApprove = computed(() => {
    return (
      proxy.$permission('purchPlan:ratify') &&
      proxy.$store.state.permission.systemConfig.allow_purch_plan_approval ==
        1 &&
      infoList.value.data.status == 2
    )
  })
  //驳回
  const canReject = computed(() => {
    return (
      proxy.$permission('purchPlan:reject') &&
      proxy.$store.state.permission.systemConfig.allow_purch_plan_approval ==
        1 &&
      infoList.value.data.status == 2
    )
  })
  //拒绝
  const canRefuse = computed(() => {
    return (
      proxy.$permission('purchPlan:refuse') &&
      proxy.$store.state.permission.systemConfig.allow_purch_plan_approval ==
        1 &&
      infoList.value.data.status == 2
    )
  })
  //撤回
  const canRecall = computed(() => {
    return (
      proxy.$permission('purchPlan:revoke') &&
      (infoList.value.data.status == 2 ||
        (infoList.value.data.status == 7 &&
          proxy.$store.state.permission.systemConfig
            .allow_purch_plan_approval == 0))
    )
  })
  //修改
  const canModifyApplication = computed(() => {
    return (
      proxy.$permission('purchPlan:modifyApplication') &&
      (infoList.value.data.status == 7)
    )
  })
  const canUpdate = computed(() => {
    return (
      proxy.$permission('purchPlan:update') &&
      (infoList.value.data.status == 1 || infoList.value.data.status == 4)
    )
  })
  // 销审
  const canSalesReview = computed(() => {
    return (
      proxy.$permission('purchPlan:cancelCheck') &&
      infoList.value.data.status == 7 &&
      proxy.$store.state.permission.systemConfig.allow_purch_plan_approval !=
        0
    )
  })
  const canPrint = computed(() => {
    return proxy.$permission('purchPlan:print') && infoList.value.data.status != 1
  })
  function handelMethodRequest(row = undefined, method) {
    const ids = [row.id]
    if (method === 'submit') {
        let data = {
            flowTaskCommentDto: { approvalType: 'submit' },
            processDefinitionKey: 'purchPlan',
            orderIds: ids,
        }
        methodPurchPlan(data, method).then((resp) => {
            if (resp && resp.success) {
              if (proxy.$route.query.processInstanceId) {
                proxy.$fn.setFlowPath(proxy)
                return
              }
              refreshDetail()
            }
        })
    } else if (method === 'reject') {
        proxy
            .$prompt('请输入驳回理由', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: proxy.$fn.maxString200,
                inputErrorMessage: '驳回理由不能超过200字符',
            })
            .then(({ value }) => {
                const data = {
                    id: row.id,
                    orderId: row.id,
                    checkOpt: value,
                }
                methodPurchPlan(data, method).then((resp) => {
                    if (resp && resp.success) {
                        refreshDetail()
                    }
                })
            })
    } else if (method === 'refuse') {
        proxy
            .$prompt('请输入拒绝理由', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: proxy.$fn.maxString200,
                inputErrorMessage: '拒绝理由不能超过200字符',
            })
            .then(({ value }) => {
                const data = {
                    id: row.id,
                    orderId: row.id,
                    checkOpt: value,
                }
                methodPurchPlan(data, method).then((resp) => {
                    if (resp && resp.success) {
                        refreshDetail()
                    }
                })
            })
    } else if (method === 'approved') {
        methodPurchPlan({ orderIds: ids }, method).then((resp) => {
            if (resp.success) {
                refreshDetail()
            }
        })
    } else {
        methodPurchPlan(ids, method).then((resp) => {
            if (resp.success) {
                if (proxy.$route.query.processInstanceId) {
                  proxy.$fn.setFlowPath(proxy)
                  return
                }
                refreshDetail()
            }
        })
    }
}
  function update() {
    modifyInfo.value.orderId = infoList.value.data.id
    modifyInfo.value.title = '修改采购计划'
    modifyInfo.value.visible = true
    modifyInfo.value.isDisabled = false
  }
  function modifyApplication(){
    modifyInfo.value.title = '修改申请'
    modifyInfo.value.orderId = infoList.value.data.id
    modifyInfo.value.visible = true
    modifyInfo.value.isDisabled = true
  }
  function returnBack() {
    emits('returnBack', false)
  }
  function refreshDetail() {
    getMain()
    getList()
  }
  function getMain() {
    getPurchPlanById(props.id).then((resp) => {
      if (resp && resp.success) {
        infoList.value.data = resp.data
        showFieldList('planQuarter', resp.data.planCycle == '2')
        showFieldList('planMonth', resp.data.planCycle == '3')
        showFieldList('planStartDate', resp.data.planCycle !== '4')
        showFieldList('planEndDate', resp.data.planCycle !== '4')
        showFieldList('planAmount', resp.data.planDimension == '1')
        showFieldList('rangeIdValue', resp.data.planRange == '2')
        showFieldList('limitBusiness', resp.data.planCycle !== '4' || resp.data.isLimit == '1')
        showFieldList('criticalValue', resp.data.planCycle !== '4' || resp.data.isCriticalRemind == '1')
        if(resp.data.planDimension == '2'){
            getList()
        }
      }
    })
  }
  function showFieldList(str, val) {
    infoList.value.fieldList.map(item => {
        if (item.value === str) {
            item.show = val
        }
    })
}
  function getList() {
    console.log(filterInfo.value.query)
    getPurchProductDetail(filterInfo.value.query).then(
      (resp) => {
        if (resp && resp.success) {
          tableInfo.value.data = resp.data
        }
      }
    )
  }
  
  //导出excel
  async function exportExcel() {
    excelpurchPlanOrder(filterInfo.value.query).then((resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    })
  }
  
  const templateArr = ref([])
  const popoverVisible = ref(false)
  //打印
  function print() {
    selectByCodeAndDept({
      tempCode: 'purchPlanDetail',
    }).then((res) => {
      if (res && res.success) {
        templateArr.value = res.data
        popoverVisible.value = true
        // 一条数据则直接打印
        if (templateArr.value.length === 1) {
          proxy.$refs.popoverShow.hidePopover()
          doPrint({
            name: templateArr.value[0].ureportName,
            params: {
                purchPlanId: infoList.value.data.id,
              orderId: infoList.value.data.id,
              orderNo: infoList.value.data.orderNo,
            },
            callback: printCallback,
            data: {},
          })
        }
      }
    })
  }
  function printCallback() {}
  function tempClick(item) {
    doPrint({
      name: item.ureportName,
      params: {
        purchPlanId: infoList.value.data.id,
        orderId: infoList.value.data.id,
        orderNo: infoList.value.data.orderNo,
      },
      callback: printCallback,
      data: {},
    })
    popoverVisible.value = false
  }
  </script>
  
  <style scoped></style>
  